import * as THREE from 'three';
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { Draggable } from './draggable';
import { Common } from '@/utils/three/xThree';

class Css2dObject {
  constructor(viewer) {
    this.viewer = viewer;
    this.meshs = null;
    this.draggableMeshs = [];
    this.init();
  }
  init() {
    this.meshs = new THREE.Group();
    this.meshs.name = 'cssObjectGroup';
    this.viewer.scene.add(this.meshs);
  }

  // 新添加的方法 position = {x:0,y:0,z:0,}
  add(element, { name, position, draggable = false }) {
    const cssObject = new CSS2DObject(element);
    cssObject.name = name;
    cssObject.draggable = draggable;
    const x = this.viewer.container?.offsetWidth / 2;
    const y = this.viewer.container?.offsetHeight / 2;
    const point = position || Common.getPointByScreen(this.viewer, x, y);
    cssObject.position.set(point.x, point.y, point.z);
    this.meshs.add(cssObject);
    if (draggable) {
      const draggableMesh = new Draggable(this.viewer, cssObject);
      this.draggableMeshs.push(draggableMesh);
    }
    return cssObject;
  }

  show(key, name, visible = false) {
    this.meshs.children.forEach((item) => {
      if (item[key] == name) {
        item.visible = visible;
      }
    });
  }

  remove(key, name) {
    for (var i = this.meshs.children.length - 1; i >= 0; i--) {
      if (this.meshs.children[i][key] == name) {
        this.meshs.remove(this.meshs.children[i]);
      }
    }
  }

  removeAll() {
    for (var i = this.meshs.children.length - 1; i >= 0; i--) {
      this.meshs.remove(this.meshs.children[i]);
    }
    this.viewer.scene.remove(this.meshs);
  }

  showAll(visible) {
    this.meshs.children.forEach((item) => {
      item.visible = visible;
    });
  }
}
export { Css2dObject };
